﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UcAsp.Net.Model;
using UcAsp.Net.Comm;
using UcAsp.Net.Interface;
using UcAsp.Net.DALFactory;
namespace UcAsp.Net.Web.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
        private static readonly ICache cache = DALFactory.CacheAccess.CreateCache();
        public ActionResult Index()
        {
            IsAdminLogin();
            List<Model.Theme> list = new BLL.ThemeConfig().GetList();
            return View();
        }
        #region 皮肤管理
        public ActionResult ThemesManage()
        {
            IsAdminLogin();
            List<Theme> list = new BLL.ThemeConfig().GetList();

            return View(list);
        }
        public ActionResult SelectThemes()
        {
            IsAdminLogin();
            string theme = Request.QueryString["theme"];
            string mobiletheme = Request.QueryString["mobiletheme"];
            Message message = new Message { Result = true, Note1 = "" };

            Model.SiteSetting site = BLL.SettingConfig.GetSiteSetting;
            if (!string.IsNullOrEmpty(theme))
            {
                site.Theme = theme;
            }
            if (!string.IsNullOrEmpty(mobiletheme))
            {
                site.MobileTheme = mobiletheme;
            }
            BLL.SettingConfig.SaveSiteSetting(site);
            cache.RemoveAllCache();
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        public ActionResult EditAdv()
        {
            IsAdminLogin();
            string theme = Request["Theme"].ToString();
            AdvPositions adv = new AdvPositions();
            if (Request["advname"] == null)
            {

            }
            else
            {
                if (!string.IsNullOrEmpty(Request["Message"]))
                {
                    adv = BLL.AdvConfig.GetAdvMessagePositions(Request["advname"], Request["Id"].ToString(), theme);
                }
                else if (Request["id"] == "0" || string.IsNullOrEmpty(Request["id"]))
                {
                    adv = BLL.AdvConfig.GetAdvPositions(Request["advname"], theme);
                }
                else
                {
                    adv = BLL.AdvConfig.GetAdvPositions(Request["advname"], Request["Id"].ToString(), theme);
                }
            }
            return View(adv);
        }
        public ActionResult AdvManage()
        {
            IsAdminLogin();
            List<Model.AdvPositions> adv = new List<AdvPositions>();
            string theme = Request["Theme"].ToString();
            if (string.IsNullOrEmpty(Request["Id"]))
            {
                adv = BLL.AdvConfig.GetListAdvPositions(theme);
                ViewData["Id"] = "0";
            }
            else
            {
                if (!string.IsNullOrEmpty(Request["Message"]))
                {
                    adv = BLL.AdvConfig.GetListAdvMessagePositions(Request["Id"].ToString(), theme);
                }
                else
                {
                    adv = BLL.AdvConfig.GetListAdvCategoriesPositions(Request["Id"].ToString(), theme);
                }
                ViewData["Id"] = Request["Id"].ToString();
            }
            return View(adv);
        }
        [ValidateInput(false)]
        public ActionResult SaveAdv(AdvPositions model)
        {
            IsAdminLogin();
            string theme = Request["Theme"].ToString();
            if (Request.Form["CId"].ToString() == "0")
            {
                BLL.AdvConfig.SaveAdvPositions(model, theme);
            }
            else
            {
                if (!string.IsNullOrEmpty(Request["Message"]))
                {
                    BLL.AdvConfig.SaveAdvMessagePositions(model, Request.Form["CId"].ToString(), theme);
                }
                else
                {
                    BLL.AdvConfig.SaveAdvCategoriesPositions(model, Request.Form["CId"].ToString(), theme);
                }
            }
            Message message = new Message { Result = true };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        [ValidateInput(false)]
        public ActionResult SaveAdmin(AdminUser model)
        {
            IsAdminLogin();
            model.LastLoginTime = DateTime.Now;
            model.LoginTime = DateTime.Now;
            new BLL.AdminUserBLL().Update(model);
            Message message = new Message { Result = true };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        public ActionResult SubjectManage()
        {
            IsAdminLogin();
            List<Model.Subjects> subject = new List<Subjects>();
            string theme = Request["Theme"].ToString();
            if (string.IsNullOrEmpty(Request["CId"]))
            {
                subject = BLL.SubjectsConfig.GetListSubjects(theme);
                ViewData["CId"] = "0";
            }
            else
            {
                if (Request["Message"] != null)
                {
                    subject = BLL.SubjectsConfig.GetMessageSubjects(int.Parse(Request["CId"].ToString()), theme);
                }
                else
                {
                    subject = BLL.SubjectsConfig.GetCategoriesSubjects(int.Parse(Request["CId"].ToString()), theme);

                } ViewData["CId"] = Request["CId"].ToString();
            }
            return View(subject);
        }
        public ActionResult EditSubject()
        {
            IsAdminLogin();
            int id = int.Parse(Request.QueryString["subjectid"].ToString());
            string theme = Request["Theme"].ToString();
            Model.Subjects subject = new Subjects();
            string[] list = new BLL.ThemeConfig().SubjectTheme();
            IEnumerable<string> accessIDs = list;

            SelectList selectlist = new SelectList(accessIDs);

            ViewData["selectlist"] = selectlist;
            if (Request["CId"] == null)
            {
                subject = BLL.SubjectsConfig.GetSubjects(id, theme);
                if (subject == null) subject = new Subjects();
                ViewData["CId"] = "0";
            }
            else
            {
                if (Request["CId"].ToString() == "0")
                {

                    subject = BLL.SubjectsConfig.GetSubjects(id, theme);
                    if (subject == null) subject = new Subjects();
                    ViewData["CId"] = "0";
                }
                else
                {
                    string cid = Request["CId"].ToString();
                    if (Request["Message"] != null)
                    {
                        subject = BLL.SubjectsConfig.GetMessageSubjects(id, int.Parse(cid), theme);
                        if (subject == null) subject = new Subjects();
                    }
                    else
                    {
                        subject = BLL.SubjectsConfig.GetSubjects(id, int.Parse(cid), theme);
                        if (subject == null) subject = new Subjects();
                    }
                    ViewData["CId"] = cid;
                }

            }
            ViewData["Categories"] = new BLL.CategoriesBLL().GetCategoriessComBox();
            return View(subject);
        }
        [ValidateInput(false)]
        public ActionResult SaveSubject(Subjects model)
        {
            IsAdminLogin();
            string theme = Request["Theme"].ToString();
            string _categories = Request.Form["Categories[]"].ToString();
            model.Categories = _categories;
            Message message = new Message { Result = true };
            if (Request.Form["CId"].ToString() == "0")
            {
                if (model.SubjectId != 0)
                {
                    BLL.SubjectsConfig.SaveSubjects(model, theme);
                }
                else
                {
                    Subjects endsubject = BLL.SubjectsConfig.GetListSubjects(theme).OrderByDescending(o => o.SubjectId).FirstOrDefault();
                    if (endsubject == null)
                    {
                        model.SubjectId = 1;
                    }
                    else
                    {
                        model.SubjectId = endsubject.SubjectId + 1;
                    }
                    BLL.SubjectsConfig.InsertSubject(model, theme);
                }


            }
            else
            {
                if (!string.IsNullOrEmpty(Request["Message"]))
                {
                    if (model.SubjectId != 0)
                    {
                        BLL.SubjectsConfig.SaveMessageSubjects(model, Request.Form["CId"].ToString(), theme);
                    }
                    else
                    {
                        Subjects endsubject = BLL.SubjectsConfig.GetMessageSubjects(int.Parse(Request.Form["CId"].ToString()), theme).OrderByDescending(o => o.SubjectId).FirstOrDefault();
                        if (endsubject == null)
                        {
                            model.SubjectId = 1;
                        }
                        else
                        {
                            model.SubjectId = endsubject.SubjectId + 1;
                        }
                        BLL.SubjectsConfig.InsertMessageSubjects(model, Request.Form["CId"].ToString(), theme);
                    }
                }
                else
                {

                    if (model.SubjectId != 0)
                    {
                        BLL.SubjectsConfig.SaveCategoriesSubjects(model, Request.Form["CId"].ToString(), theme);
                    }
                    else
                    {
                        Subjects endsubject = BLL.SubjectsConfig.GetCategoriesSubjects(int.Parse(Request.Form["CId"].ToString()), theme).OrderByDescending(o => o.SubjectId).FirstOrDefault();
                        if (endsubject == null)
                        {
                            model.SubjectId = 1;
                        }
                        else
                        {
                            model.SubjectId = endsubject.SubjectId + 1;
                        }
                        BLL.SubjectsConfig.InsertCategoriesSubjects(model, Request.Form["CId"].ToString(), theme);
                    }
                }
                cache.GetCache("Subject" + Request.Form["CId"].ToString());
                cache.GetCache("Subjects" + Request.Form["CId"].ToString());
            }

            return Json(message, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DeleteSubject()
        {
            IsAdminLogin();
            Message message = new Message { Result = true };
            string theme = Request["Theme"].ToString();
            string subjectId = Request.Form["subjectId"].ToString();
            if (Request.Form["CId"].ToString() == "0")
            {
                BLL.SubjectsConfig.DeleteSubjects(subjectId, theme);
            }
            else
            {
                if (!string.IsNullOrEmpty(Request.Form["Message"]))
                {
                    BLL.SubjectsConfig.DeleteMessageSubjects(subjectId, Request.Form["CId"].ToString(), theme);
                }
                else
                {
                    BLL.SubjectsConfig.DeleteCategoriesSubjects(subjectId, Request.Form["CId"].ToString(), theme);
                }
                cache.GetCache("Subject" + Request.Form["CId"].ToString());
                cache.GetCache("Subjects" + Request.Form["CId"].ToString());
            }

            return Json(message, JsonRequestBehavior.AllowGet);
        }
        public ActionResult CategoriesThemes()
        {
            IsAdminLogin();
            int id = 0;
            ViewData["ParentID"] = 0;
            if (Request.QueryString["ID"] != null)
            {
                id = int.Parse(Request.QueryString["ID"].ToString());
                ViewData["ParentID"] = id;
            }


            ViewData["Categories"] = new BLL.CategoriesBLL().GetCategoriessPath(id);
            return View(new BLL.CategoriesBLL().GetCategoriessComBox());
        }
        #endregion
        [HttpGet]
        public ActionResult Login()
        {
            if (Request.QueryString["url"] != null)
            {
                ViewData["url"] = Request.QueryString["url"].ToString();
            }
            else
            {
                ViewData["url"] = "";
            }
            ViewData["code"] = (Convert.ToBoolean(DateTime.Now.Ticks / 10000)).ToString();
            return View();
        }
        public ActionResult ModifyAdmin()
        {
            IsAdminLogin();
            BLL.AdminUserBLL admin = new BLL.AdminUserBLL();
            return View(admin.GetAdminByUserName(Session["Admin"].ToString()));
        }
        [HttpPost]
        public ActionResult PostAdmin()
        {
            IsAdminLogin();
            BLL.AdminUserBLL bll = new BLL.AdminUserBLL();
            AdminUser user = bll.GetAdminByUserName(Session["Admin"].ToString());
            string password = Request.Form["UserPassword"].ToString();

            user.UserPassword = password;
            bll.Update(user);
            Message message = new Message { Result = true, Messages = "修改成功" };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult PostLogin()
        {
            Message message = new Message { Result = false, Messages = "用户或密码错误" };
            string username = Request.Form["UserName"];
            string password = Request.Form["Password"];
            string code = Request.Form["Code"];
            string url = Request.Form["Url"];
            string msg = string.Empty;
            message.Result = new BLL.AdminUserBLL().Login(username, password, out msg);
            message.Messages = msg;
            message.Note1 = Session.SessionID;
            if (!string.IsNullOrEmpty(url.Trim()))
            {
                if (url.IndexOf("?") > 0)
                { url = url + "&"; }
                message.Note2 = url;
            }
            else
            {
                message.Note2 = "/Admin/Index/?";
            }
            if (message.Result == true)
            {
                Session["Admin"] = username;
            }
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        public ActionResult LoginOut()
        {
            Session.RemoveAll();
            return Redirect("/");
        }
        public ActionResult SiteSetting()
        {
            IsAdminLogin();
            return View(BLL.SettingConfig.GetSiteSetting);
        }
        [ValidateInput(false)]
        public ActionResult SaveSetSetting(SiteSetting model)
        {
            IsAdminLogin();
            BLL.SettingConfig.SaveSiteSetting(model);
            Message message = new Message { Result = true, Messages = "信息完成更新" };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        #region 分类管理
        public ActionResult CategoriesManger()
        {
            IsAdminLogin();
            int id = 0;
            ViewData["ParentID"] = 0;
            if (Request.QueryString["ID"] != null)
            {
                id = int.Parse(Request.QueryString["ID"].ToString());
                ViewData["ParentID"] = id;
            }


            ViewData["Categories"] = new BLL.CategoriesBLL().GetCategoriessPath(id);
            return View(new BLL.CategoriesBLL().GetCategoriessComBox());
        }
        public ActionResult CategoriesDelete()
        {
            IsAdminLogin();
            int id = 0;
            if (Request.QueryString["ID"] != null)
            {
                id = int.Parse(Request.QueryString["ID"].ToString());
            }
            new BLL.CategoriesBLL().Delete(id);
            Message message = new Message { Result = true };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetCategories()
        {
            IsAdminLogin();
            int id = 0;
            if (Request.QueryString["ID"] != null)
            {
                id = int.Parse(Request.QueryString["ID"].ToString());
            }
            int page;
            List<Categories> list = new BLL.CategoriesBLL().Select(id, 200, 0, out page);
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        public ActionResult EditCategories()
        {
            IsAdminLogin();
            int page;
            List<Categories> list = new List<Categories>();
            if (Request.QueryString["ParentID"] != null)
            {
                if (Request.QueryString["ParentID"].ToString().Trim() != string.Empty)
                {
                    int pid = int.Parse(Request.QueryString["ParentID"].ToString());
                    if (pid != 0)
                    {
                        Categories c = new BLL.CategoriesBLL().GetCategoriesById(pid);
                        list = new BLL.CategoriesBLL().Select(c.ParentID, 200, 0, out page);
                    }
                    else { list = new BLL.CategoriesBLL().Select(0, 200, 0, out page); }

                }
                else
                {
                    list = new BLL.CategoriesBLL().Select(0, 200, 0, out page);

                }
            }
            else
            {
                list = new BLL.CategoriesBLL().Select(0, 200, 0, out page);
            }


            IEnumerable<Categories> accessIDs = list;
            list.Insert(0, (new Categories { ID = 0, CategorieName = "选择分类" }));

            SelectList selectlist = new SelectList(accessIDs, "ID", "CategorieName");

            ViewData["selectlist"] = selectlist;



            string[] categorieslist = new BLL.ThemeConfig().CategoriesTheme();
            IEnumerable<string> accesscategoriess = categorieslist;

            ViewData["categorieslist"] = new SelectList(accesscategoriess);

            string[] messagelist = new BLL.ThemeConfig().ShowMessageTheme();
            IEnumerable<string> accessmessage = messagelist;

            ViewData["contentlist"] = new SelectList(accessmessage);

            Categories categories = new Categories();
            int id = 0;
            if (Request.QueryString["ID"] != null)
            {
                id = int.Parse(Request.QueryString["ID"].ToString());
                categories = new BLL.CategoriesBLL().GetCategoriesById(id);
            }
            ViewData["Categories"] = new BLL.CategoriesBLL().GetCategoriessComBox();
            return View(categories);

        }

        [ValidateInput(false)]
        public ActionResult SaveCategories(Categories model)
        {
            IsAdminLogin();

            if (model.ID == 0)
            {

                new BLL.CategoriesBLL().Insert(model);
            }
            else
            {
                new BLL.CategoriesBLL().Update(model);

            }

            Message message = new Message { Result = true, Messages = "" };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region 字段设置
        public ActionResult EditSetFiled()
        {
            IsAdminLogin();
            SetFiled model = new SetFiled();
            int id = 0;
            ViewData["CID"] = Request.QueryString["CID"].ToString();
            List<string> list = new List<string>();

            list.Insert(0, "CategorieID");
            list.Insert(1, "Title");
            list.Insert(2, "Tag");
            list.Insert(3, "ArticleContent");
            list.Insert(4, "IconUrl");
            list.Insert(5, "MetaKeyword");
            list.Insert(6, "MetaDescrition");
            list.Insert(7, "Description");
            list.Insert(8, "AddDatetime");
            list.Insert(9, "ModifyDatetime");
            list.Insert(10, "IsRelease");
            list.Insert(11, "IsRecommend");
            list.Insert(12, "Rate");
            list.Insert(13, "Rank");


            list.Insert(14, "Note1");
            list.Insert(15, "Note2");
            list.Insert(16, "Note3");
            list.Insert(17, "Note4");
            list.Insert(18, "Note5");
            list.Insert(19, "Note6");
            list.Insert(20, "Note7");
            list.Insert(21, "Note8");
            list.Insert(22, "Note9");


            list.Insert(23, "Int1");
            list.Insert(24, "Int2");
            list.Insert(25, "Int3");
            list.Insert(26, "Int4");
            list.Insert(27, "Int5");



            list.Insert(28, "Float1");
            list.Insert(29, "Float2");
            list.Insert(30, "Float3");
            list.Insert(31, "Float4");
            list.Insert(32, "Float5");

            list.Insert(33, "Date1");
            list.Insert(34, "Date2");
            list.Insert(35, "Date3");
            list.Insert(36, "Date4");
            list.Insert(37, "Date5");
            list.Insert(38, "Date6");
            list.Insert(39, "Date7");
            list.Insert(40, "Date8");

            list.Insert(41, "ViewsTemp");
            list.Insert(42, "ShowPath");
            list.Insert(43, "Rank");

            IEnumerable<string> accessIDs = list;
            SelectList selectlist = new SelectList(accessIDs);

            ViewData["selectlist"] = selectlist;
            if (Request.QueryString["ID"] != null)
            {
                id = int.Parse(Request.QueryString["ID"].ToString());
                model = new BLL.SetFiledBLL().Limit(id);
            }
            return View(model);
        }
        [ValidateInput(false)]
        public ActionResult SaveSetFiled(SetFiled model)
        {
            IsAdminLogin();
            bool Result = false;
            if (model.FiledID == 0)
            {

                Result = new BLL.SetFiledBLL().Insert(model);
            }
            else
            {
                Result = new BLL.SetFiledBLL().Update(model);

            }

            Message message = new Message { Result = Result, Messages = "" };
            return Json(message, JsonRequestBehavior.AllowGet);

        }

        public ActionResult SetFiledManger()
        {
            IsAdminLogin();
            int id = int.Parse(Request.QueryString["CID"].ToString());
            List<SetFiled> list = new BLL.SetFiledBLL().Select(id);
            return View(list);
        }
        public ActionResult UpdateSetFiledRank()
        {
            IsAdminLogin();
            Message message = new Message();
            message.Result = true;
            int id = int.Parse(Request.Form["ID"].ToString());
            bool down = Request.Form["action"].ToString().Equals("down");
            SetFiled file = new BLL.SetFiledBLL().Limit(id);
            if (!down)
            {
                if (file.Rank <= 1)
                {
                    message.Result = false;
                    return Json(message, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    file.Rank--;

                    new BLL.SetFiledBLL().Update(file);
                    return Json(message, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                file.Rank++;
                new BLL.SetFiledBLL().Update(file);
                return Json(message, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult DeleteSetFiled()
        {
            IsAdminLogin();
            int id = int.Parse(Request.Form["ID"].ToString());
            SetFiled file = new BLL.SetFiledBLL().Limit(id);
            new BLL.SetFiledBLL().Delete(file);
            Message message = new Message();
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region 内容管理
        public ActionResult ArticlesManager()
        {
            IsAdminLogin();
            EditArtices html = new EditArtices();
            string jsxt = string.Empty;
            Articles model = new Model.Articles();
            if (Request.QueryString["ID"] != null)
            {
                model = new BLL.ArticlesBLL().GetArticles(int.Parse(Request.QueryString["ID"].ToString()));
            }
            else
            {
                model.CategorieID = int.Parse(Request.QueryString["CID"].ToString());
            }
            string image = string.Empty;

            html.EditHTML = new UcAsp.Net.BLL.ArticlesBLL().ArticesView(model.CategorieID, out jsxt, model, out image);
            html.EditJS = jsxt;
            ViewData["image"] = image;
            return View(html);
        }
        public ActionResult ArticlesExpress()
        {
            IsAdminLogin();
            string image = string.Empty;
            EditArtices html = new EditArtices();
            string jsxt = string.Empty;
            Articles model = new Model.Articles();
            model.CategorieID = int.Parse(BLL.SysParamBLL.GetParamByName("Express"));
            html.EditHTML = new UcAsp.Net.BLL.ArticlesBLL().ArticesView(model.CategorieID, out jsxt, model, out image);
            html.EditJS = jsxt;
            return View(html);
        }
        public ActionResult SaveExpress()
        {
            IsAdminLogin();
            string content = Request.Form["Content"].ToString();
            string[] list = content.Split('\n');
            for (int i = 0; i < list.Length; i++)
            {
                string[] express = list[i].Split('\t');
                Model.Articles model = new Articles { Title = express[0], Note1 = express[1], Note2 = express[2], Note3 = express[3], Note4 = express[4], Note5 = express[5], Note6 = express[6], Note7 = express[7], Date1 = DateTime.Parse(express[8]), AddDatetime = DateTime.Now, CategorieID = int.Parse(BLL.SysParamBLL.GetParamByName("Express")) };
                Model.Articles exit = new BLL.ArticlesBLL().GetArtieByTitle(model.Title);
                if (exit == null)
                {
                    new BLL.ArticlesBLL().Insert(model);
                }

            }
            Message message = new Message { Result = true };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        public ActionResult DeleteExpress()
        {
            IsAdminLogin();
            new BLL.ArticlesBLL().Delete(DateTime.Now.AddDays(-5), int.Parse(BLL.SysParamBLL.GetParamByName("Express")));
            Message message = new Message { Result = true };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        [ValidateInput(false)]
        public ActionResult SaveArtices(Articles model)
        {
            IsAdminLogin();
            if (model.IconUrl == "nofile")
                model.IconUrl = "";
            if (model.ID == 0)
            {

                Model.Articles exit = new BLL.ArticlesBLL().GetArtieByTitle(model.Title);
                if (exit == null)
                {
                    new BLL.ArticlesBLL().Insert(model);
                }
            }
            else
            {
                new BLL.ArticlesBLL().Update(model);
            }
            Message message = new Message { Result = true, Note1 = model.ID.ToString() };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        [ValidateInput(false)]
        public ActionResult CheckArtices(Articles model)
        {
            IsAdminLogin();
            bool isExit = false;
            string Id = "0";
            Model.Articles exit = new BLL.ArticlesBLL().GetArtieByTitle(model.Title);
            if (exit != null)
            {
                isExit = true;
                Id = exit.ID.ToString();
            }
            Message message = new Message { Result = isExit, Note1 = Id };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        [ValidateInput(false)]
        public ActionResult SaveArticlesPage(ArticlesPage model)
        {
            IsAdminLogin();
            model.AddDateTime = DateTime.Now;
            if (model.IconUrl == "nofile")
                model.IconUrl = "";
            if (model.ID == 0)
            {
                Articles art = new BLL.ArticlesBLL().GetArticles(model.ArticlesID);

                ArticlesPage page = new BLL.ArticlesPageBLL().GetArticlesPageByPageID(model.ArticlesID, model.PageID);
                if (page == null)
                {
                    new BLL.ArticlesPageBLL().Insert(model);
                }
            }
            else
            {
                new BLL.ArticlesPageBLL().Update(model);
            }
            Message message = new Message { Result = true, Note1 = model.ID.ToString() };
            return Json(message, JsonRequestBehavior.AllowGet);
        }

        public ActionResult EditArticlesPage()
        {
            int count;
            List<ArticelsViews> list;
            IsAdminLogin();
            Model.ArticlesPage page = new ArticlesPage();
            if (Request.QueryString["ID"] != null)
            {
                int id = int.Parse(Request.QueryString["ID"].ToString());
                page = new BLL.ArticlesPageBLL().GetArticlesPageByID(id);
            }
            else if (Request.QueryString["ArticlesID"] != null)
            {
                page.ArticlesID = int.Parse(Request.QueryString["ArticlesID"].ToString());
                page.CategoriesID = new BLL.ArticlesBLL().GetArtieById(page.ArticlesID, out count, out list).CategorieID;
            }
            return View(page);
        }
        /// <summary>
        /// 检测文件是否已经添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult CheckArticlesPage(ArticlesPage model)
        {
            IsAdminLogin();
            bool isExit = false;

            Articles art = new BLL.ArticlesBLL().GetArticles(model.ArticlesID);
            ArticlesPage page = new BLL.ArticlesPageBLL().GetArticlesPageByPageID(model.ArticlesID, model.PageID);
            if (page == null)
            {
                isExit = false;
            }
            else
            {
                isExit = true;
            }

            Message message = new Message { Result = isExit };
            return Json(message, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Articles()
        {
            IsAdminLogin();
            int? id = null;
            int? userid = null;
            if (!string.IsNullOrEmpty(Request.QueryString["CID"]))
            {

                id = int.Parse(Request.QueryString["CID"].ToString());
                ViewData["CID"] = "&CID=" + id;

            }
            int pageindex = Convert.ToInt16(Request.QueryString["PageIndex"]) == 0 ? 1 : Convert.ToInt16(Request.QueryString["PageIndex"]);
            int pagecount = 0;
            List<ArticelsViews> list = new List<ArticelsViews>();
            if (string.IsNullOrEmpty(Request.QueryString["UserID"]))
            {
                //list = new BLL.ArticlesBLL().SelectViews(null, id, 20, pageindex - 1, out pagecount);
                ViewData["UserID"] = "";
            }
            else
            {
                userid = int.Parse(Request.QueryString["UserID"].ToString());
                // list = new BLL.ArticlesBLL().SelectViews(, id, 20, pageindex - 1, out pagecount);
                ViewData["UserID"] = "&UserID=" + Request.QueryString["UserID"].ToString();

            }
            if (!string.IsNullOrEmpty(Request.QueryString["keyword"]))
            {
                list = new BLL.ArticlesBLL().SelectViews(userid, id, null, null, null, null, Request.QueryString["keyword"].ToString(), 20, pageindex - 1, out pagecount);
                ViewData["UserID"] = ViewData["UserID"] + "&keyword=" + Request.QueryString["keyword"].ToString();
            }
            else
            {
                list = new BLL.ArticlesBLL().SelectViews(userid, id, 20, pageindex - 1, out pagecount);
            }

            ViewData["PageCount"] = pagecount;
            ViewData["Pre"] = pageindex - 1 > 0 ? pageindex - 1 : 1;
            ViewData["Next"] = pageindex + 1 < pagecount ? pageindex + 1 : pagecount;

            return View(list);
        }
        public ActionResult ArticlesRecommad()
        {
            IsAdminLogin();
            int id = int.Parse(Request.Form["ID"].ToString());
            Articles articles = new BLL.ArticlesBLL().GetArticles(id);
            bool result = articles.IsRecommend == true ? false : true;
            articles.IsRecommend = result;
            new BLL.ArticlesBLL().Update(articles);
            Message message = new Message { Result = true, Messages = "" };
            return Json(message, JsonRequestBehavior.AllowGet);

        }
        public ActionResult ArticlesRelease()
        {
            IsAdminLogin();
            int id = int.Parse(Request.Form["ID"].ToString());
            Articles articles = new BLL.ArticlesBLL().GetArticles(id);
            bool result = articles.IsRelease == true ? false : true;
            articles.IsRelease = result;
            new BLL.ArticlesBLL().Update(articles);
            Message message = new Message { Result = true, Messages = "" };
            return Json(message, JsonRequestBehavior.AllowGet);

        }
        public ActionResult ArticlesDel()
        {
            IsAdminLogin();
            int id = int.Parse(Request.Form["ID"].ToString());
            new BLL.ArticlesBLL().Delete(id);
            Message message = new Message();
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        public ActionResult ArticlesPageManager()
        {
            IsAdminLogin();
            int id = int.Parse(Request.QueryString["ID"].ToString());
            List<ArticlesPage> list = new BLL.ArticlesPageBLL().GetArticlesPageByArticlesID(id);
            ViewData["PageId"] = id.ToString();
            return View(list);
        }
        #endregion
        public ActionResult Command()
        {
            IsAdminLogin();
            int pageindex = 0;
            int pagesize = 20;
            int pagecount = 0;
            if (Request.QueryString["PageIndex"] != null)
            {
                pageindex = int.Parse(Request.QueryString["PageIndex"].ToString());
            }
            ViewData["PageCount"] = pagecount;
            ViewData["Pre"] = pageindex - 1 > 0 ? pageindex - 1 : 1;
            ViewData["Next"] = pageindex + 1 < pagecount ? pageindex + 1 : pagecount;
            List<Comments> list = new BLL.CommentsBLL().Select(0, pageindex, pagesize, out pagecount);
            return View(list);
        }
        #region 用户管理
        public ActionResult Custom()
        {
            IsAdminLogin();
            List<UserInfo> list = new List<UserInfo>();
            int pageindex = 0;
            int pagesize = 20;
            int pagecount = 0;
            if (Request.QueryString["PageIndex"] != null)
            {
                pageindex = int.Parse(Request.QueryString["PageIndex"].ToString());
            }
            ViewData["PageCount"] = pagecount;
            ViewData["Pre"] = pageindex - 1 > 0 ? pageindex - 1 : 1;
            ViewData["Next"] = pageindex + 1 < pagecount ? pageindex + 1 : pagecount;
            if (Request.QueryString["keyword"] != null)
            {
                list = new BLL.UserInfoBLL().SelectByKeyword(pagesize, pageindex, out pagecount, Request.QueryString["keyword"].ToString()).ToList();
            }
            else
            {
                list = new BLL.UserInfoBLL().Select(pagesize, pageindex, out pagecount).ToList();
            }
            return View(list);
        }
        public ActionResult EditCustom()
        {
            IsAdminLogin();
            Message message = new Message { Result = true };
            int id = int.Parse(Request.QueryString["ID"].ToString());

            UserInfo user = new BLL.UserInfoBLL().GetUserInfoByID(id);
            int i = (int)user.UserLevel;
            return View(user);
        }
        public ActionResult DelCustom()
        {
            IsAdminLogin();
            Message message = new Message { Result = true };
            int id = int.Parse(Request.Form["ID"].ToString());

            new BLL.UserInfoBLL().Delete(id);
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        public ActionResult CustomSave(UserInfo model)
        {
            IsAdminLogin();
            UserInfo user = BLL.UserInfoBLL.GetInstance.GetUserInfoByID(model.ID);
            user.UserLevel = model.UserLevel;
            user.Point = model.Point;
            user.UserName = model.UserName;
            BLL.UserInfoBLL.GetInstance.Update(user);
            Message message = new Message { Result = true };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        #endregion
        /// <summary>
        /// 自定义页面
        /// </summary>
        /// <returns></returns>
        public ActionResult UserDefined()
        {
            IsAdminLogin();
            return View(BLL.UserDefinedConfig.GetListUserDefinedConfig);
        }
        public ActionResult DefinedManager()
        {
            IsAdminLogin();
            Model.UserDefined userdefined = new UserDefined();
            if (Request.QueryString["Name"] != null)
            {
                userdefined = BLL.UserDefinedConfig.GetUserDefined(Request.QueryString["Name"].ToString());
            }
            string[] list = new BLL.UserDefinedConfig().DefinedView();
            IEnumerable<string> accessIDs = list;

            SelectList selectlist = new SelectList(accessIDs);

            ViewData["selectlist"] = selectlist;
            return View(userdefined);
        }

        #region 系统字典管理
        public ActionResult DefinedCode()
        {
            IsAdminLogin();
            int pageindex = 0;
            int pagesize = 20;
            int pagecount = 0;
            if (Request.QueryString["PageIndex"] != null)
            {
                pageindex = int.Parse(Request.QueryString["PageIndex"].ToString());
            }

            ViewData["Pre"] = pageindex - 1 > 0 ? pageindex - 1 : 1;
            ViewData["Next"] = pageindex + 1 < pagecount ? pageindex + 1 : pagecount;
            List<DefinedCode> list = new BLL.DefinedCodeBLL().Select(pagesize, pageindex, out pagecount).ToList();
            ViewData["PageCount"] = pagecount;
            return View(list);
        }
        public ActionResult EditDefinedCode()
        {
            IsAdminLogin();
            int id = 0;
            Model.DefinedCode model = new Model.DefinedCode();
            if (Request.QueryString["ID"] != null)
            {
                id = int.Parse(Request.QueryString["ID"].ToString());
                model = new BLL.DefinedCodeBLL().GetDefinedCodeName(id);
            }

            return View(model);
        }
        [ValidateInput(false)]
        public ActionResult SaveDefinedCode(DefinedCode model)
        {
            IsAdminLogin();
            model.AddDate = DateTime.Now;
            if (model.ID == 0)
            {
                new BLL.DefinedCodeBLL().Insert(model);
            }
            else
            {
                new BLL.DefinedCodeBLL().Update(model);
            }
            Message message = new Message { Result = true };
            return Json(message, JsonRequestBehavior.AllowGet);

        }
        public ActionResult DelDefinedCode()
        {
            IsAdminLogin();
            int id = int.Parse(Request.Form["ID"].ToString());
            new BLL.DefinedCodeBLL().Delete(new BLL.DefinedCodeBLL().GetDefinedCodeName(id));
            Message message = new Message { Result = true };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        #endregion
        [ValidateInput(false)]
        public ActionResult SaveDefined(UserDefined model)
        {
            IsAdminLogin();
            UserDefined defined = BLL.UserDefinedConfig.GetUserDefined(model.DefinedName);
            if (defined == null)
            {
                BLL.UserDefinedConfig.InsertConfig(model);
            }
            else
            {
                BLL.UserDefinedConfig.UpdateConfig(model);
            }
            Message message = new Message { Result = true };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        public ActionResult SysParam()
        {
            IsAdminLogin();
            int pageindex = 1;
            int pagesize = 20;
            int pagecount = 0;
            if (Request.QueryString["PageIndex"] != null)
            {
                pageindex = int.Parse(Request.QueryString["PageIndex"].ToString());
                if (pageindex <= 0)
                {
                    pageindex = 1;
                }

            }


            List<SysParam> list = new BLL.SysParamBLL().Select(pagesize, pageindex, out pagecount).ToList();

            ViewData["Pre"] = pageindex - 1 > 0 ? pageindex - 1 : 1;
            ViewData["Next"] = pageindex + 1 < pagecount ? pageindex + 1 : pagecount;
            ViewData["PageCount"] = pagecount;
            return View(list);

        }
        public ActionResult EditSysParam()
        {
            IsAdminLogin();
            int id = 0;
            Model.SysParam model = new Model.SysParam();
            if (Request.QueryString["ID"] != null)
            {
                id = int.Parse(Request.QueryString["ID"].ToString());
                model = new BLL.SysParamBLL().GetParamById(id);
            }

            return View(model);
        }
        public ActionResult SysParamSave(SysParam model)
        {
            IsAdminLogin();
            if (model.ID == 0)
            {
                new BLL.SysParamBLL().Insert(model);
            }
            else
            {
                new BLL.SysParamBLL().Update(model);
            }
            Message message = new Message { Result = true };
            return Json(message, JsonRequestBehavior.AllowGet);

        }
        public ActionResult SysParamDel()
        {
            IsAdminLogin();
            int id = int.Parse(Request.Form["ID"].ToString());
            new BLL.SysParamBLL().Delete(id);
            Message message = new Message { Result = true };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Course()
        {
            IsAdminLogin();
            int pageindex = 0;
            int pagesize = 20;
            int pagecount = 0;
            if (Request.QueryString["PageIndex"] != null)
            {
                pageindex = int.Parse(Request.QueryString["PageIndex"].ToString());
            }
            ViewData["PageCount"] = pagecount;
            ViewData["Pre"] = pageindex - 1 > 0 ? pageindex - 1 : 1;
            ViewData["Next"] = pageindex + 1 < pagecount ? pageindex + 1 : pagecount;
            List<Course> list = new BLL.CourseBLL().Select(pagesize, pageindex, out pagecount).ToList();
            return View(list);
        }
        public ActionResult EditCourse()
        {
            IsAdminLogin();
            int id = 0;
            Model.Course model = new Model.Course();
            if (Request.QueryString["ID"] != null)
            {
                id = int.Parse(Request.QueryString["ID"].ToString());
                model = new BLL.CourseBLL().GetCourseByID(id);
            }
            return View(model);
        }
        public ActionResult DelCourse()
        {
            IsAdminLogin();
            int id = int.Parse(Request.Form["ID"].ToString());
            new BLL.CourseBLL().Delete(id);
            Message message = new Message { Result = true };
            return Json(message, JsonRequestBehavior.AllowGet);

        }
        public ActionResult CourseSave(Course model)
        {
            IsAdminLogin();
            if (model.ID == 0)
            {
                new BLL.CourseBLL().Insert(model);
            }
            else
            {
                new BLL.CourseBLL().Update(model);
            }
            Message message = new Message { Result = true };
            return Json(message, JsonRequestBehavior.AllowGet);

        }
        public ActionResult CourseDel()
        {
            IsAdminLogin();
            int id = int.Parse(Request.Form["ID"].ToString());
            new BLL.CourseBLL().Delete(id);
            Message message = new Message { Result = true };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        public ActionResult CssManager()
        {
            IsAdminLogin();
            string[] list = new BLL.CssConfig().GetCssList(Request["theme"].ToString());
            return View(list);
        }
        public ActionResult EditCss()
        {
            IsAdminLogin();
            string theme = Request["theme"].ToString();
            string cssname = Request["cssname"].ToString();
            Object content = new BLL.CssConfig().GetCss(theme, cssname);
            return View(content);
        }
        [ValidateInput(false)]
        public ActionResult SaveCss()
        {
            IsAdminLogin();
            string theme = Request["theme"].ToString();
            string cssname = Request["cssname"].ToString();
            string content = Request["content"].ToString();
            new BLL.CssConfig().WriteCss(theme, cssname, content);
            Message message = new Message { Messages = "保存成功" };
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        public void IsAdminLogin()
        {
            if (Request.QueryString["Security"] != null)
            {
                string code = Comm.Encrypt.DecodeEncrypt(Request.QueryString["Security"].ToString());
                string[] result = code.Split('|');
                DateTime clienttime = DateTime.Parse(result[1]);
                TimeSpan ts = DateTime.Now - clienttime;
                if (ts.Minutes < 10)
                {
                    if (!result[0].Equals(BLL.SysParamBLL.GetParamByName("Security")))
                    { Response.Redirect("/admin/Login"); Response.End(); }

                }
                else
                {
                    Response.Redirect("/admin/Login");
                    Response.End();
                }
            }
            else
            {
                string url = Url.Encode(Request.Url.ToString());
                if (Session["Admin"] == null)
                {
                    Response.Redirect("/admin/Login?url=" + url);
                    Response.End();
                }
            }

            return;
        }
    }

}
